import { useEffect, useState, ComponentType } from 'react';

const withLoader = <P extends object>(Element: ComponentType<P>, url: string) => {
  return (props: P): JSX.Element => {
    const [data, setData] = useState<string[]>([]);

    useEffect(() => {
      async function getData() {
        const res = await fetch(url);
        const jsonData = await res.json();
        setData(jsonData.message);
      }

      getData();
    }, []);

    if (!data.length) {
      return <div>Loading...</div>;
    }

    return <Element {...props} data={data} />;
  };
};

export default withLoader;
